<template>
  <t-drawer
    v-model:visible="formVisible"
    size="medium"
    size-draggable
    :footer="false"
    :header="isEdit ? '编辑' : '新增'"
  >
    <div>
      <t-form ref="formRef" :data="form" :rules="rules" @submit="onSubmit">
        <t-form-item name="username" label="用户名">
          <t-input v-model="form.username" placeholder="请填写用户名" />
        </t-form-item>
        <t-form-item v-if="!isEdit" name="password" label="密码">
          <t-input v-model="form.password" placeholder="请填写密码" />
        </t-form-item>
        <t-form-item name="orgId" label="所属机构">
          <t-tree-select
            v-model="form.orgId"
            :keys="{
              label: 'name',
              value: 'id',
            }"
            :data="treeData"
            clearable
            placeholder="请选择组织机构"
          ></t-tree-select>
        </t-form-item>
        <t-form-item name="roleIds" label="角色">
          <t-checkbox-group v-model="form.roleIds">
            <!-- 角色的id 和 名称 -->
            <t-checkbox v-for="{ roleName, id } in roles" :key="id" :value="id" :label="roleName"></t-checkbox>
          </t-checkbox-group>
        </t-form-item>
        <t-form-item name="station" label="岗位">
          <t-input v-model="form.station" placeholder="请填写岗位" />
        </t-form-item>
        <t-form-item name="section" label="部门">
          <t-input v-model="form.section" placeholder="请填写部门" />
        </t-form-item>
        <t-form-item name="age" label="年龄">
          <t-input v-model="form.age" type="number" placeholder="请填写年龄" />
        </t-form-item>
        <t-form-item name="sex" label="性别">
          <t-radio-group v-model="form.sex">
            <t-radio value="1">男</t-radio>
            <t-radio value="2">女</t-radio>
          </t-radio-group>
        </t-form-item>
        <t-form-item name="phone" label="手机号">
          <t-input v-model="form.phone" placeholder="请填写手机号" />
        </t-form-item>
        <t-form-item name="lockFlag" label="是否锁定">
          <t-radio-group v-model="form.lockFlag">
            <t-radio value="1">是</t-radio>
            <t-radio value="0">否</t-radio>
          </t-radio-group>
        </t-form-item>
        <t-form-item>
          <t-button variant="outline" @click="close">取消</t-button>
          <t-button theme="primary" type="submit">确定</t-button>
        </t-form-item>
      </t-form>
    </div>
  </t-drawer>
</template>

<script lang="ts" setup>
import { MessagePlugin, SubmitContext } from 'tdesign-vue-next';
import { computed, ref } from 'vue';
import { useRequest } from 'vue-request';

import { getOrgTree } from '@/api/upms/org';
import { getRoleList } from '@/api/upms/role';
import { saveUserInfo, updateUserInfo } from '@/api/upms/user';
import { useVisible } from '@/hooks/visible';

const { data: treeData } = useRequest(getOrgTree);

const { data: roles } = useRequest(getRoleList);

const formRef = ref();

const initData = () => {
  return {
    id: '',
    roleCodes: '',
    username: '',
    password: '',
    orgId: '',
    orgName: '',
    roleIds: [] as Array<string>,
    phone: '',
    // 其他
    userType: 0,
    lockFlag: '0',
    station: '',
    section: '',
    age: '',
    sex: '',
  };
};

const rules = {
  username: [
    {
      required: true,
      message: '用户名不能为空',
    },
  ],
  password: [
    {
      required: true,
      message: '密码不能为空',
    },
    { minLength: 8, message: '密码长度至少为8位' },
  ],
  orgId: [
    {
      required: true,
      message: '组织机构不能为空',
    },
  ],
  roleIds: [
    {
      required: true,
      message: '角色不能为空',
    },
  ],
  station: [
    {
      required: true,
      message: '岗位不能为空',
    },
  ],
  section: [
    {
      required: true,
      message: '部门不能为空',
    },
  ],
  age: [
    {
      required: true,
      message: '年龄不能为空',
    },
  ],
  sex: [
    {
      required: true,
      message: '性别不能为空',
    },
  ],
};

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  formData: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const emit = defineEmits<{
  (e: 'update:visible', v: boolean): void;
  (e: 'refresh'): void;
}>();

const form = ref(props.formData);

const { formVisible, close, open } = useVisible(props, emit);

// 判断是编辑还是新增
const isEdit = computed(() => !!form.value.id);

const onSubmit = async (ctx: SubmitContext) => {
  if (ctx.validateResult === true) {
    form.value.roleCodes = roles.value
      .filter((item: any) => form.value.roleIds.includes(item.id))
      .map((item: any) => item.roleCode);
    if (isEdit.value) {
      await updateUserInfo(form.value).then(() => {
        MessagePlugin.success('修改成功');
      });
    } else {
      await saveUserInfo(form.value).then(() => {
        MessagePlugin.success('添加成功');
      });
    }
    form.value = { ...initData };
    formVisible.value = false;
    emit('refresh');
  } else {
    MessagePlugin.warning(ctx.firstError);
  }
};

open(() => {
  const { id } = props.formData;
  if (id) {
    form.value = props.formData;
  } else {
    form.value = initData();
  }
});
</script>
